import requests
import time, os

import pandas as pd
import matplotlib.pyplot as plt
import schedule


# print(self.base)
# 基金基础信息
# https://query.sse.com.cn/commonQuery.do?jsonCallBack=jsonpCallback17501112&isPagination=true&sqlId=COMMON_SSE_ZQPZ_ETFZL_ETFJBXX_JJGM_MOREN_L&SEC_CODE=511130&pageHelp.pageSize=10&_=1729497750488

##sqlid = COMMON_SSE_CP_JJLB_ETFJJGK_GGSGSHQD_JBXX_C
# https://query.sse.com.cn/commonQuery.do?jsonCallBack=jsonpCallback61564432&isPagination=false&FUNDID2=511130&sqlId=COMMON_SSE_CP_JJLB_ETFJJGK_GGSGSHQD_JBXX_C&_=1729497750489

# 基金持仓
# https://query.sse.com.cn/commonQuery.do?jsonCallBack=jsonpCallback80279178&isPagination=true&FUNDID2=511130&sqlId=COMMON_SSE_CP_JJLB_ETFJJGK_GGSGSHQD_COMPONENT_C&pageHelp.pageSize=10&pageHelp.cacheSize=1&pageHelp.pageNo=1&pageHelp.beginPage=1&pageHelp.endPage=1&_=1729497750490


## 这是一个访问SSE.com.cn去获取ETf基金数据的类
# 1、更新快照数据，并存储本地，快照数据存储在snap中
# 2、更新历史数据，并存储本地，历史数据存储在his中
# 3、更新持仓数据，并存储本地，历史数据存储在hive中
# 4、更新基金基础数据，并存储本地，历史数据存储在base中

class SigleEft30:
    # etf 代码
    dm = "511130"
    snap = {}  # 最新数据信息
    line = {}  # 每日线性数据
    base = {}  # 基础数据 包含净值 NAV
    nav = 0.000  # 持仓数据
    last = 0.00
    checkprice = 104.843
    wl = last - checkprice

    def __init__(self, dm):
        self.dm = dm

    def refreshsnap(self):
        t = int(round(time.time() * 1000))

        # 定义需要从API请求中获取的字段列表
        snap_fields = [
            "name", "code", "last", "chg_rate", "change", "amount", "volume",
            "open", "prev_close", "ask", "bid", "high", "low",
            "tradephase", "turnover_ratio", "totalValue", "amp_rate",
            "circulating", "up_limit", "down_limit", "hlt_tag",
            "gdr_ratio", "gdr_prevpx", "gdr_currency"
        ]

        # 将字段列表中的每个字段用 %2C 连接起来
        snap_select = "%2C".join(snap_fields)
        snapurl = "https://yunhq.sse.com.cn:32042/v1/sh1/snap/{}?select={}&_={}".format(self.dm, snap_select, t)
        header = {
            "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/117.0}"}

        response = requests.get(snapurl, headers=header)

        responsejson = response.json()
        # 取出responsejson中snap的内容，与fields的项一一对应
        self.snap["date"] = responsejson["date"]
        self.snap["time"] = responsejson["time"]
        for i in range(len(snap_fields)):
            self.snap[snap_fields[i]] = str(responsejson["snap"][i])
        self.last = float(self.snap["last"])
        self.wl = self.last - self.checkprice

    def refshline(self):
        print("===========//=============")
        # 早上8:00-9:15分不更新趋势线
        if time.localtime().tm_hour < 9 or time.localtime().tm_hour > 20:
            return False
        t = int(round(time.time() * 1000))
        # time%2Cprice%2Cvolume%2Cavg_price%2Camount%2Chighest%2Clowest
        line_fields = ["time", "price", "volume", "avg_price", "amount", "highest", "lowest"]
        line_select = "%2C".join(line_fields)

        lineurl = "https://yunhq.sse.com.cn:32042/v1/sh1/line/{}?select={}&_={}".format(self.dm, line_select, t)

        header = {
            "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/117.0}"}
        response = requests.get(lineurl, headers=header)
        responsejson = response.json()
        #print("line:", responsejson["line"])
        self.line = responsejson["line"]
        # 实现这个函数30秒自动更新一次

    def refreshbase(self):
        t = int(round(time.time() * 1000))
        sqlid = "COMMON_SSE_CP_JJLB_ETFJJGK_GGSGSHQD_JBXX_C"
        header = {
            "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/117.0}",
            "cookie": "gdp_user_id=gioenc-87613g72%2Ce26b%2C58b5%2C867d%2Cc4c593e019b6; ba17301551dcbaf9_gdp_session_id=df36bb84-a573-47b8-8c56-daf2af88d888; ba17301551dcbaf9_gdp_session_id_sent=df36bb84-a573-47b8-8c56-daf2af88d888; JSESSIONID=53D828F578664784218B30B7B3026C5E; ba17301551dcbaf9_gdp_sequence_ids={%22globalKey%22:425%2C%22VISIT%22:4%2C%22PAGE%22:24%2C%22VIEW_CHANGE%22:3%2C%22CUSTOM%22:2%2C%22VIEW_CLICK%22:396}",
            "content-type": "application/json;charset=UTF-8",
            "Referer": "https://www.sse.com.cn/",
            "Host": "query.sse.com.cn"
            }

        base_url = "https://query.sse.com.cn/commonQuery.do?&isPagination=false&FUNDID2={}&sqlId={}&_={}".format(
            self.dm, sqlid, t)
        response = requests.get(base_url, headers=header)
        # print(response.text)
        self.base = response.json()["result"][0]
        self.nav = round(float(self.base["NAV"].replace("￥", "")), 3)
        # print("//////////////////////")

    def watch_etf(self):
        output = []
        self.refshline()
        for line in self.line:
            linetime = f"{str(line[0])[:2]}:{str(line[0])[2:4]}:{str(line[0])[4:]}"
            if line[2] > 1000000:  # 大于1亿交易额
                output.append({"time": linetime, "price": line[1], "direction": "买入", "level": "推荐(高级)"})
            if line[2] > 500000 and line[2] <= 1000000:
                output.append({"time": linetime, "price": line[1], "direction": "买入", "level": "推荐(中级)"})
            if line[2] > 200000 and line[2] <= 500000:
                output.append({"time": linetime, "price": line[1], "direction": "买入", "level": "推荐(低级)"})
        return output
# etf30 = SigleEft30(dm="511130")
# etf30.refreshsnap()
# #print(etf30.snap)
# etf30.refshline()
# etf30.refreshbase()
# print(etf30.base)
#
# # 每 30 秒执行一次 refshline 函数
# while True:
#     time.sleep(5)
#     os.system('cls')
#     etf30.refreshsnap()
#     #print(etf30.snap)
#     etf30.refshline()
#     etf30.watch_etf()
#     ps="当前：{}  距离购入价格{} , 距离{},盈亏：{}元".format(etf30.last,etf30.checkprice,round(etf30.wl,3),round(etf30.wl*3700,3))
#     print(ps)
